package thread.blocking.demo;

import encrypt.demo.AESUtils;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.concurrent.LinkedBlockingQueue;

public class ProcessJob implements  Runnable{
    //入队列
    private LinkedBlockingQueue<User> queue;
    //出队列
    private BlockingHashMap<Long,User> map;

    public ProcessJob(LinkedBlockingQueue<User> queue, BlockingHashMap<Long,User> map){
        this.queue = queue;
        this.map = map;
    }

    @Override
    public void run() {
        Cipher AES_cipher = null;
        Base64.Encoder encoder = null;
        try {
            AES_cipher = Cipher.getInstance(AESUtils.TRANSFORMATION);
            encoder = Base64.getEncoder();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        while (true){
            try {

                System.out.println(Thread.currentThread().getName()+":wait for new msg");
                //获取数据
                User user = this.queue.take();

                //假装处理数据，放入密文字段
                System.out.println(Thread.currentThread().getName()+":msg processing..... ");
                Key key = AESUtils.generateKey(user.getKey());
                AES_cipher.init(Cipher.ENCRYPT_MODE,key);

                user.setSalary_mi(encoder.encodeToString(AES_cipher.doFinal(user.getSalary().getBytes())));


                byte[] data = user.getData();
                String encoded = Base64.getEncoder().encodeToString(data);
                user.setDataBase64(encoded);




                //将数据返回前台线程
                this.map.put(user.getUserId(),user);
                //完事进入下一循环
                System.out.println(Thread.currentThread().getName()+":processed finished.");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
